{ TSM Intraday High-Low
   Copyright 2011 P.J. Kaufman.  All rights reserved.
	Based on the idea that the open, then the close, are the most likely times
	for the high or low of the day }
	
{	enteronbar = enter on close of this bar
	mingap = 	minimum close-to-Open gap
	returnoption = 0 for Price difference, 1 for percentage
	exitoption = 0 for Exit on close
					 1 for use volatility exit + close
}

	Inputs: 	Enteronbar(2), endtime(1500), mingap(0.005), returnoption(1), exitoption(0);
	vars:		trigger(false), gapdirection(0), nbar(0), size(1), investment(25000),
				thigh(0), tlow(0), entryhigh(0), entrylow(0), gap(0);
	
{ Test for new day. }
	If Date <> date[1] then begin	
			nbar = 1;
			trigger = False;
			gapdirection = 0;
			thigh = high;
			tlow = low;
			entryhigh = 0;
			entrylow = 0;
			if open > close[1] then gapdirection = 1 
				else if Open < close[1] then gapdirection = -1;
			If returnoption = 0 then gap = absvalue(Open - close[1])
				else if returnoption = 1 then gap = absvalue(open/close[1] - 1);
			If gap > mingap then trigger = true;
			End
		Else begin
			nbar = nbar + 1;
			thigh = maxlist(thigh,high);
			tlow = minlist(tlow,low);
		end;
		
{ test for end of day exit }
	If Time >= endtime then begin
		If Marketposition > 0 then sell ("SEOD") all contracts this bar on close
			Else if Marketposition < 0 then buy to cover ("BEOD") all contracts this bar on close;
		end;	
		
{ stop or reverse position if high-low penetrated }
	If Marketposition > 0 and low < tlow[1] then begin
			Sell ("Sstop") all contracts this bar on close;
			Sell short ("Srev") size contracts this bar on close;
			End
		Else if marketposition < 0 and high > thigh[1] then begin
			Buy to cover ("Bstop") all contracts this bar on close;
			Buy ("Brev") size contracts this bar on close;
		end;		
		
{ test for entry }
	If trigger and nbar = Enteronbar then begin
		If gapdirection > 0 then sell short size contracts this bar on close
			else if gapdirection < 0 then buy size contracts this bar on close;
		entryhigh = thigh;
		entrylow = tlow;
		end; 
				
	If Currentbar = 1 then begin
			print (file("c:\TSM5\Intraday high-low.csv"), 
					"Date,Time,Bar,Open,High,Low,Close,",
					"tHigh,tLow,Gap,Gapdirection,trigger,signal");
			Print (file("c:\TSM5\Intraday high-low daily PL.csv"),
					"Date,netPL");
			end
		else begin
			print (file("c:\TSM5\Intraday high-low.csv"),
					date:8:0, ",", time:5:0, ",", nbar:5:0, ",", 
					open:5:5, ",", high:5:5, ",", low:5:5, ",", close:5:5, ",",
					thigh:5:5, ",", tlow:5:5, ",", gap:5:5, ",", 
					gapdirection:5:0, ",", trigger, ",", marketposition:5:0);
			If Date <> date[1] then begin
				Print (file("c:\TSM5\Intraday high-low daily PL.csv"), 
					date:8:0, ",", netprofit:10:0);
				end;
		end;
			
					
				